package inet.app.view.activity;

import inet.app.R;
import inet.app.controller.parser.Parser;
import inet.app.controller.parser.Parser_Push_MB;
import inet.app.controller.parser.Parser_Push_NT;
import inet.app.model.object.KqGiai_Item;
import inet.app.model.util.Util;
import inet.app.view.adapter.KetQuaDetailAdapter;
import inet.app.view.fragment.FragmentMB;
import inet.app.view.fragment.FragmentMN;
import inet.app.view.fragment.FragmentMT;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class KetQuaFragment extends BaseFragmentActivity implements
		OnClickListener {
	private RelativeLayout rlAdsHeader, rlAdsFooter;
	private int countPushMN = 0, countPushMT = 0, countPushMB = 0;
	private ViewPager _mViewPager;
	private KetQuaDetailAdapter _adapter;
	private ArrayList<KqGiai_Item> push;
	private FragmentMB fmb;
	// XSSYNC_RESP|0|09/01/2014
	// 14:50:22|XSTD||1:70062|2:12258-77026|3:53165-62463-53272|4:|5:|6:|7:|8:|0:||

	private FragmentMT fmt;
	private FragmentMN fmn;
	int Yellow1 = Color.rgb(255, 255, 0);
	int Red1 = Color.rgb(255, 0, 0);
	int heavyblue = Color.rgb(0, 0, 255);
	private ArrayList<Fragment> list_Fragment;
	private String json = null;
	public int posCurrent = 1;
	int demtrang = 1;
	int max = 10;
	private LinearLayout first_text, second_text, three_text;
	private TextView tvTitle, tvNhamang;
	static final String duongdan = "KhoiTao";
	SharedPreferences pref;
	SharedPreferences.Editor editor;
	boolean isFirstCreate;
	private List<ChangePagerListener> mChangePageListeners = new ArrayList<KetQuaFragment.ChangePagerListener>();

	// private Handler myUpdateHandler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.ketqua_fragment);
		Loadabout();
		initBase();
		initUI();
		initFragment();
		init_ViewPager();
		setTab();

		// Push notify
		this.pushThread = new Thread(new KQTTThread());
		this.pushThread.start();
	}

	@Override
	protected void onStart() {
		super.onStart();
		// startUpdateHandler();
		// startThread();
	}

	private void Loadabout() {
		pref = getSharedPreferences(duongdan, 0);
		isFirstCreate = pref.getBoolean("isFirstCreate", true);
		if (isFirstCreate) {
			pref = getSharedPreferences(duongdan, 0);
			editor = pref.edit();
			editor.putBoolean("isFirstCreate", false);
			editor.commit();
			helpDialog(KetQuaFragment.this);
		}
	}

	private void initUI() {
		rlAdsHeader = (RelativeLayout) findViewById(R.id.rlAdsHeader);
		rlAdsFooter = (RelativeLayout) findViewById(R.id.rlAdsFooter);
		// rlAdsFooter.setVisibility(View.VISIBLE);
		// rlAdsHeader.setVisibility(View.VISIBLE);
		findViewById(R.id.btCloseAdsHeader).setOnClickListener(this);
		// findViewById(R.id.btCloseAdsFooter).setOnClickListener(this);

		first_text = (LinearLayout) findViewById(R.id.first_text);
		second_text = (LinearLayout) findViewById(R.id.second_text);
		three_text = (LinearLayout) findViewById(R.id.three_text);
		first_text.setOnClickListener(this);
		second_text.setOnClickListener(this);
		three_text.setOnClickListener(this);
		tvTitle = (TextView) findViewById(R.id.tvTitle);
		tvNhamang = (TextView) findViewById(R.id.tvNhamang);
		tvNhamang.setText(Util.getSharePreferences(KetQuaFragment.this));

		_mViewPager = (ViewPager) findViewById(R.id.viewPager);
		list_Fragment = new ArrayList<Fragment>();

	}

	private void initFragment() {
		Bundle rb = this.getIntent().getExtras();
		String json = rb.getString("json");
		posCurrent = rb.getInt("pos");
		if (!json.equals("")) {
			if (posCurrent == 0) {
				fmb = (FragmentMB) FragmentMB.newInstance(this,
						posCurrent + "", json);
				fmt = (FragmentMT) FragmentMT.newInstance(this);
				fmn = (FragmentMN) FragmentMN.newInstance(this);
				first_text.setBackgroundResource(R.drawable.sub_tab1_2);
				second_text.setBackgroundResource(R.drawable.sub_tab2);
				three_text.setBackgroundResource(R.drawable.sub_tab1);
			} else if (posCurrent == 1) {
				fmb = (FragmentMB) FragmentMB.newInstance(this);
				fmt = (FragmentMT) FragmentMT
						.newInstance(this, posCurrent + "");
				fmn = (FragmentMN) FragmentMN.newInstance(this);
			} else if (posCurrent == 2) {
				fmb = (FragmentMB) FragmentMB.newInstance(this);
				fmt = (FragmentMT) FragmentMT.newInstance(this);
				fmn = (FragmentMN) FragmentMN
						.newInstance(this, posCurrent + "");
			}

			list_Fragment.add(fmb);
			list_Fragment.add(fmt);
			list_Fragment.add(fmn);
		} else {
			System.out.println("NO UPDATE ==========>> NOT QUIT APP");
		}
	}

	public void init_ViewPager() {
		FragmentManager fm = getSupportFragmentManager();
		_adapter = new KetQuaDetailAdapter(this, _mViewPager, fm, list_Fragment);
		_mViewPager.setAdapter(_adapter);
		_mViewPager.setCurrentItem(posCurrent);
		if (Util.onLiveTime_MB()) {
			_mViewPager.setCurrentItem(0);
			first_text.setBackgroundResource(R.drawable.sub_tab1_2);
			second_text.setBackgroundResource(R.drawable.sub_tab2);
			three_text.setBackgroundResource(R.drawable.sub_tab1);
			tvTitle.setText("Kết Quả Miền Bắc");
		} else if (Util.onLiveTime_MT()) {
			_mViewPager.setCurrentItem(1);
			first_text.setBackgroundResource(R.drawable.sub_tab1);
			second_text.setBackgroundResource(R.drawable.sub_tab2_2);
			three_text.setBackgroundResource(R.drawable.sub_tab1);
			tvTitle.setText("Kết Quả Miền Trung");
		} else if (Util.onLiveTime_MN()) {
			_mViewPager.setCurrentItem(2);
			first_text.setBackgroundResource(R.drawable.sub_tab1);
			second_text.setBackgroundResource(R.drawable.sub_tab2);
			three_text.setBackgroundResource(R.drawable.sub_tab1_2);
			tvTitle.setText("Kết Quả Miền Nam");
		} else {
			_mViewPager.setCurrentItem(0);
			first_text.setBackgroundResource(R.drawable.sub_tab1_2);
			second_text.setBackgroundResource(R.drawable.sub_tab2);
			three_text.setBackgroundResource(R.drawable.sub_tab1);
			tvTitle.setText("Kết Quả Miền Bắc");
		}
	}

	private void setTab() {
		_mViewPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageScrollStateChanged(int position) {
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
			}

			@Override
			public void onPageSelected(int position) {

				// notify to all fragment
				for (ChangePagerListener listener : mChangePageListeners) {
					if (listener != null) {
						listener.onChange(position);
					}
				}

				switch (position) {
				case 0:
					posCurrent = 0;
					fmb = (FragmentMB) _adapter.getItem(0);
					first_text.setBackgroundResource(R.drawable.sub_tab1_2);
					second_text.setBackgroundResource(R.drawable.sub_tab2);
					three_text.setBackgroundResource(R.drawable.sub_tab1);
					tvTitle.setText("Kết Quả Miền Bắc");
					_mViewPager.setCurrentItem(0);
					break;
				case 1:
					posCurrent = 1;
					fmt = (FragmentMT) _adapter.getItem(1);
					first_text.setBackgroundResource(R.drawable.sub_tab1);
					second_text.setBackgroundResource(R.drawable.sub_tab2_2);
					three_text.setBackgroundResource(R.drawable.sub_tab1);
					tvTitle.setText("Kết Quả Miền Trung");
					// if (fmt.isNull())
					// fmt.Update();
					_mViewPager.setCurrentItem(1);
					break;
				case 2:
					posCurrent = 2;
					fmn = (FragmentMN) _adapter.getItem(2);
					first_text.setBackgroundResource(R.drawable.sub_tab1);
					second_text.setBackgroundResource(R.drawable.sub_tab2);
					three_text.setBackgroundResource(R.drawable.sub_tab1_2);
					tvTitle.setText("Kết Quả Miền Nam");
					// if (fmn.isNull())
					// fmn.Update();
					_mViewPager.setCurrentItem(2);
					break;
				}
			}

		});

	}

	@Override
	public void onResume() {
		if (((MyApp) getApplication()).isKill()) {
			stopThread();
			finish();
		}
		// Intent intent = new Intent(this, PushLiveService.class);
		// startService(intent);
		super.onResume();
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			System.out.println("THOAT NHE");
			showQuitDialog(KetQuaFragment.this);
			dlquit.show();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	protected void hideMenu() {
		if (slideMenuAnimationContainer.isOpening()) {
			slideMenuAnimationContainer.closeSlideMenu();
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.first_text:
			posCurrent = 0;
			fmb = (FragmentMB) _adapter.getItem(0);
			first_text.setBackgroundResource(R.drawable.sub_tab1_2);
			second_text.setBackgroundResource(R.drawable.sub_tab2);
			three_text.setBackgroundResource(R.drawable.sub_tab1);
			tvTitle.setText("Kết Quả Miền Bắc");
			_mViewPager.setCurrentItem(0);
			break;
		case R.id.second_text:
			posCurrent = 1;
			fmt = (FragmentMT) _adapter.getItem(1);
			first_text.setBackgroundResource(R.drawable.sub_tab1);
			second_text.setBackgroundResource(R.drawable.sub_tab2_2);
			three_text.setBackgroundResource(R.drawable.sub_tab1);
			tvTitle.setText("Kết Quả Miền Trung");
			// if (fmt.isNull())
			// fmt.Update();
			_mViewPager.setCurrentItem(1);
			break;
		case R.id.three_text:
			posCurrent = 2;
			fmn = (FragmentMN) _adapter.getItem(2);
			first_text.setBackgroundResource(R.drawable.sub_tab1);
			second_text.setBackgroundResource(R.drawable.sub_tab2);
			three_text.setBackgroundResource(R.drawable.sub_tab1_2);
			tvTitle.setText("Kết Quả Miền Nam");
			// if (fmn.isNull())
			// fmn.Update();
			_mViewPager.setCurrentItem(2);
			break;
		case R.id.btCloseAdsHeader:
			rlAdsHeader.setVisibility(View.GONE);
			break;
		case R.id.btCloseAdsFooter:
			rlAdsFooter.setVisibility(View.GONE);
			break;
		default:
			break;
		}
	}

	public void aboutDialog(Context c) {
		about = new Dialog(c);
		about.setTitle("              Thông Tin");
		about.setContentView(R.layout.dialog_about);
		Button dong = (Button) about.findViewById(R.id.btAboutClose);
		dong.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				about.dismiss();
			}
		});
	}

	Handler myUpdateHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == 0) {
				Util.savePreferences("isPush", true, KetQuaFragment.this);
				json = (String) msg.obj;
				// System.out.println("JSON ==>> : " + json);
				Parser pp = new Parser();
				if (pp.getName(json).equals("XSSYNC_RESP")) {
					if (pp.getMien(json).equals("MB")) {
						System.out.println("RUN MIEN BAC");
						fmb = (FragmentMB) _adapter.getItem(0);
						Parser_Push_MB parser = new Parser_Push_MB();
						push = parser.getList(json);
						if (push != null) {
							countPushMB++;
							if (countPushMB < 2) {
								Util.savePreferences("ONLIVEMB", true,
										KetQuaFragment.this);
								_mViewPager.setCurrentItem(0);
							}
							fmb.Update_Live_MB(push);
						}
					} else if (pp.getMien(json).equals("MT")) {
						System.out.println("RUN MIEN TRUNG");
						fmt = (FragmentMT) _adapter.getItem(1);
						Parser_Push_NT parser = new Parser_Push_NT();
						push = parser.getList(json);
						if (push != null) {
							countPushMT++;
							if (countPushMT < 2) {
								Util.savePreferences("ONLIVEMT", true,
										KetQuaFragment.this);
								_mViewPager.setCurrentItem(1);
							}
							fmt.Update_Live_TN(push);
						}
					} else if (pp.getMien(json).equals("MN")) {
						System.out.println("RUN MIEN NAM");
						fmn = (FragmentMN) _adapter.getItem(2);
						Parser_Push_NT parser = new Parser_Push_NT();
						push = parser.getList(json);
						if (push != null) {
							countPushMN++;
							if (countPushMN < 2) {
								Util.savePreferences("ONLIVEMN", true,
										KetQuaFragment.this);
								_mViewPager.setCurrentItem(2);
							}
							fmn.Update_Live_MN(push);
						}
					} else {
						System.out.println("NOT TƯƠNG THUAT");
					}
				} else {
					// get kqxs fail
					Toast.makeText(KetQuaFragment.this, msg.toString(),
							Toast.LENGTH_SHORT).show();
				}
			} else if (msg.what == 1) {

			}
		};
	};

	// }

	// public void startThread() {
	// if (pushThread != null && pushThread.isAlive()) {
	// pushThread.interrupt();
	// pushThread = null;
	// }
	// pushThread = new Thread(new KQTTThread());
	// pushThread.start();
	// }

	class KQTTThread implements Runnable {
		public void run() {
			Socket s = null;
			DataInputStream _inFromMaster = null;
			byte[] buff = null;
			int buffLength;
			int bs;
			String strResult = "";
			// End
			try {
				s = ((MyApp) getApplication()).get_socket();
				// System.out.println("Giá trị của socket là  " + s);
				_inFromMaster = new DataInputStream(s.getInputStream());
				// System.out.println("Giá trị IN FORM MASTER "
				// + _inFromMaster.available());
			} catch (Exception e) {
				System.out.println(e.toString());
			}
			while (isRunning) {
				try {
					while (_inFromMaster != null
							&& _inFromMaster.available() > 0) {
						bs = _inFromMaster.available(); // get the amount of
						buff = new byte[bs];
						buffLength = buff.length;
						_inFromMaster.read(buff, 0, buffLength);
						strResult = strResult + new String(buff);
						System.out.println("PUSH LIVE ==>> : " + strResult);
						// LogFile
						// Util.Log2File(strResult);
						// if (strResult.endsWith("\r\n"))
						// break;
					}
					if (strResult != null
							&& !"".equalsIgnoreCase(strResult.trim())) {
						Message msg = myUpdateHandler.obtainMessage(0,
								strResult);
						myUpdateHandler.sendMessage(msg);
						strResult = "";
					}
				} catch (IOException ex) {
					System.out.println("CHẠY vào đây ");
					System.out.println(ex.getMessage());
					ex.fillInStackTrace();
					Message msg = myUpdateHandler.obtainMessage(1);
					myUpdateHandler.sendMessage(msg);
				}
			}
		}
	}

	public void addChangePageListener(ChangePagerListener listener) {
		mChangePageListeners.add(listener);
	}

	public void removeChangePageListener(ChangePagerListener listener) {
		if (mChangePageListeners.contains(listener)) {
			mChangePageListeners.remove(listener);
		}
	}

	public interface ChangePagerListener {
		void onChange(int page);
	}

	//
	// @Override
	// public void onStop() {
	// super.onStop();
	// stopThread();
	// myUpdateHandler.removeCallbacksAndMessages(null);
	// myUpdateHandler = null;
	// }

	// public void GetDataPush(final String code, final String response) {
	// pdia.show();
	// AsyncTask<Void, Integer, Void> myTask = new AsyncTask<Void, Integer,
	// Void>() {
	// protected Void doInBackground(Void... params) {
	// // TODO Auto-generated method stub
	// return null;
	// }
	//
	// protected void onPostExecute(Void result) {
	// super.onPreExecute();
	// pdia.dismiss();
	// }
	// };
	// myTask.execute();
	// }
}
